package com.csf.project.service.impl;

import java.sql.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.csf.project.entity.TlbbAreaDatas;
import com.csf.project.service.ISendMailService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csf.project.entity.User;
import com.csf.project.mapper.UserMapper;
import com.csf.project.msg.ObjectRestResponse;
import com.csf.project.service.AuthService;
import com.csf.project.service.UserService;

@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {

    private User currentUser;

    @Autowired
    private AuthService authService;
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;
    //注入redis服务
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    //注入邮箱服务
    @Autowired
    private ISendMailService iSendMailService;
    @Autowired
    TlbbAreaDatas tbData;
    @Override
    public User findUser(User example) {
        return userMapper.selectOne(new QueryWrapper<User>(example));
    }

    @Override
    public void loginSuccess(String username) {
        User example = new User();
        example.setUsername(username);
        currentUser = userMapper.selectOne(new QueryWrapper<User>(example));
    }

    @Override
    public User getCurrentUser() {
        return currentUser;
    }

    @Override
    public List<User> getAllUser(User user, Page<User> page) {
       return null;
    }

    @Override
    public Integer countUser(User user) {
     return null;
    }


    @Override
    public User getUserInfo(String token) {
        User example = new User();
        example.setAccesstoken(token);
        User found = userService.findUser(example);
        return found;
    }


    @Override
    public ObjectRestResponse<Object> queryData(User user){
        log.info("queryData UserServiceImpl user:{}",user);
        ObjectRestResponse<Object> resultInfo = new ObjectRestResponse<Object>();
        List<User> data = userMapper.queryData(user);
        resultInfo.setData(data);
        return resultInfo;
    }

    //检测用户是否存在
    @Override
    public Boolean checkAccount(String account) {
        User example = new User();
        example.setUsername(account);
        User found = userService.findUser(example);
        if (found == null) return false;
        return true;
    }



    //用户注册
    @Override
    public Boolean register(User user) {
        //验证注册码是否正确
        String redisCode = redisTemplate.opsForValue().get(user.getEmail()).toString();
        if (user.getUserRandCode().equals(redisCode) && !user.getUsername().isEmpty()) {
            String encoded="";
                //密码
                if (StringUtils.isBlank(user.getPassword())) {
                    encoded = authService.encodePassword(user.getUsername(), SecureUtil.md5("123456"));
                } else {
                     encoded = authService.encodePassword(user.getUsername(), SecureUtil.md5(user.getPassword()));
                }
                user.setPassword(encoded);
                //角色
                user.setRole("1");
                //user.setRealName(user.getLogin());
                //是否激活
                user.setBlocked(1);
                userMapper.insert(user);
                return true;
        }
        return false;
    }
    //用户信息修改
    public Boolean updateUserInfo(User user){
        //验证注册码是否正确
        String redisCode= redisTemplate.opsForValue().get(user.getEmail()).toString();
        if (user.getUserRandCode().equals(redisCode) && !user.getUsername().isEmpty()) {
            User example = new User();
            example.setUsername(user.getUsername());
            User found = userService.findUser(example);
            if (found == null){return false;}
            else{
                if (user.getEmail().equals(found.getEmail())){
                    user.setPassword(SecureUtil.md5(user.getPassword()));
                    user.setId(found.getId());
                    userMapper.updateById(user);
                    return true;
                }
            }
        }
        return false;
    }
    //查询游戏用户点数信息
    @Override
    public String queryUserPoint(Integer num, String account){
        //数据库配置中心
            if (!StringUtils.isBlank(account)) {
                switch (num) {
                    case 1:
                        return this.queryInfo(tbData.getOneurl(), tbData.getOneusername(), tbData.getOnepasswd(), account);
                    case 2:
                        return this.queryInfo(tbData.getTwourl(), tbData.getTwousername(), tbData.getTwopasswd(), account);
                    case 3:
                        return this.queryInfo(tbData.getThreeurl(),tbData.getThreeusername(),tbData.getThreepasswd(), account);
                    case 4:
                        return this.queryInfo(tbData.getFoururl(), tbData.getFourusername(), tbData.getFourpasswd(), account);
                    case 5:
                        return this.queryInfo(tbData.getFiveurl(), tbData.getFiveusername(), tbData.getFivepasswd(), account);
                    case 6:
                        return this.queryInfo(tbData.getSixurl(), tbData.getSixusername(), tbData.getSixpasswd(), account);
                }
                return "0";
            }
            return "0";
    }

    //修改点数
    @Override
    public String updataPoint(Integer num,String account, Integer point) {
            //数据库配置中心
            //查出用户剩余的点数
            String surPoint = this.queryUserPoint(num, account);
           if (!StringUtils.isBlank(account)) {
               switch (num) {
                   case 1:
                       return this.changePoint(tbData.getOneurl(), tbData.getOneusername(), tbData.getOnepasswd(), account, point,surPoint);
                   case 2:
                       return this.changePoint(tbData.getTwourl(), tbData.getTwousername(), tbData.getTwopasswd(), account, point,surPoint);
                   case 3:
                       return this.changePoint(tbData.getThreeurl(), tbData.getThreeusername(), tbData.getThreepasswd(), account, point,surPoint);
                   case 4:
                       return this.changePoint(tbData.getFoururl(), tbData.getFourusername(), tbData.getFourpasswd(), account, point,surPoint);
                   case 5:
                       return this.changePoint(tbData.getFiveurl(), tbData.getFiveusername(), tbData.getFivepasswd(), account, point,surPoint);
                   case 6:
                       return this.changePoint(tbData.getSixurl(), tbData.getSixusername(), tbData.getSixpasswd(), account, point,surPoint);
           }
       }
        return surPoint;
    }
    //获取redis生成随机验证码发送到邮箱
    @Override
    public Boolean getRandCode(String mail) {
        int randcode = RandomUtil.randomInt(1000, 9999);
        //随机数存入redis
        redisTemplate.opsForValue().set(mail,randcode,360,TimeUnit.SECONDS);
        //开始发送邮件到邮箱
        iSendMailService.sendHtmlMail("怀旧代理充值注册中心","您的注册验证码为："+randcode,mail);
        return true;
    }

    //处理查询游戏用户的信息
    public String  queryInfo(String url,String username,String password,String count)  {
        String point="0";
        try {
          //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接对象
            //String url = "jdbc:mysql://localhost:3306/mybase";
            //String username = "***";
            //String password = "***";
            Connection con = DriverManager.getConnection(url, username, password);

            //拼写修改的SQL语句，参数用？
            String str = count+"@game.sohu.com";
            String sql = "SELECT t.name,t.point from account t WHERE t.name = ?";
            //调用连接对象con的方法prepareStatement来获取sql语句的预编译对象
            PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql);
            pst.setObject(1, str);
            //执行SQL语句
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                point = rs.getString("point");
                log.info("查询出来的结果：{}",point);
            }
            //关闭资源
            rs.close();
            pst.close();
            con.close();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return  point;
    }

    //注册mysql驱动,修改点数
    public String changePoint(String url,String username,String password,String count,Integer point,String surPoint) {
            try {
            //注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //获取连接对象
            //String url = "jdbc:mysql://localhost:3306/mybase";
            //String username = "***";
            //String password = "***";
            Connection con = DriverManager.getConnection(url,username,password);
            //拼写修改的SQL语句，参数用？
            String sql = "Update account SET point=? WHERE name = ?";
            //调用连接对象con的方法prepareStatement来获取sql语句的预编译对象
            PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql);
            point +=Integer.parseInt(surPoint);//加上用户已有的点数
            pst.setObject(1, point);
            pst.setObject(2, count+"@game.sohu.com");
            log.info("执行修改点数Sql语句参数：",pst);
            //执行SQL语句
            int i = pst.executeUpdate();
             //关闭资源
            pst.close();
            con.close();
            if (i>0) return point.toString();
            }
            catch (Exception e) {
               e.printStackTrace();
            }
            return surPoint;
        }
}
